package com.hemaapp.yjnh.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog;
import com.hemaapp.hm_FrameWork.dialog.HemaButtonDialog.OnButtonListener;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.hemaapp.hm_FrameWork.result.HemaPageArrayResult;
import com.hemaapp.hm_FrameWork.view.RefreshLoadmoreLayout;
import com.hemaapp.yjnh.BaseActivity;
import com.hemaapp.yjnh.BaseApplication;
import com.hemaapp.yjnh.BaseHttpInformation;
import com.hemaapp.yjnh.R;
import com.hemaapp.yjnh.adapter.LaokeAdapter;
import com.hemaapp.yjnh.adapter.RecyclerTenDecoration;
import com.hemaapp.yjnh.adapter.SearchHistoryAdapter;
import com.hemaapp.yjnh.bean.Blog;
import com.hemaapp.yjnh.bean.EventBusConfig;
import com.hemaapp.yjnh.bean.EventBusMsg;
import com.hemaapp.yjnh.bean.User;
import com.hemaapp.yjnh.db.LaokeSearchDBClient;
import com.hemaapp.yjnh.listener.OnLaokeClickListener;
import com.hemaapp.yjnh.utils.LoginUtil;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import xtom.frame.util.XtomSharedPreferencesUtil;
import xtom.frame.util.XtomToastUtil;
import xtom.frame.view.XtomListView;
import xtom.frame.view.XtomRefreshLoadmoreLayout;
import xtom.frame.view.XtomRefreshLoadmoreLayout.OnStartListener;

/**
 * 唠嗑搜索
 */
public class LaokeSearchActivity extends BaseActivity implements OnLaokeClickListener, SearchHistoryAdapter.OnHistoryClickListener  {

    @Bind(R.id.edt_search)
    EditText edtSearch;
    @Bind(R.id.lstv_history)
    XtomListView lstvHistory;
    @Bind(R.id.recycler_view)
    RecyclerView recyclerView;
    @Bind(R.id.layout_refresh)
    RefreshLoadmoreLayout layoutRefresh;
    @Bind(R.id.layout_result)
    RelativeLayout layoutResult;

    private ArrayList<String> search_strs = new ArrayList<String>();
    private LaokeSearchDBClient mClient;
    private SearchHistoryAdapter historyAdapter;
    private LaokeAdapter blogAdapter;
    private User user;
    private ArrayList<Blog> blogs = new ArrayList<>();//商品/助农列表
    private Blog curBlog;//当前要操作的帖子：删除、点赞、取消赞
    private LoginUtil.LoginCallBack loginCallBack;

    private String keyword = "";
    private int page = 0;
    private String lat = "";//纬度
    private String lng = "";//经度

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_search_laoke);
        ButterKnife.bind(this);
        user = getApplicationContext().getUser();
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        lat = XtomSharedPreferencesUtil.get(mContext, "lat");
        lng = XtomSharedPreferencesUtil.get(mContext, "lng");
        mClient = new LaokeSearchDBClient(mContext);
        if (!isNull(keyword)) {//如果有传入关键词，直接进行搜索
            edtSearch.setText(keyword);
            edtSearch.setSelection(keyword.length());
        }
    }

    @Override
    protected void findView() {
    }

    @Override
    protected void getExras() {
        keyword = mIntent.getStringExtra("keyword");
    }

    @Override
    protected void onResume() {
        new LoadDBTask().execute();
        super.onResume();
    }

    @Override
    protected void setListener() {
        edtSearch.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    keyword = v.getText().toString();
                    if (isNull(keyword)) {
                        return true;
                    }
                    mInputMethodManager.hideSoftInputFromWindow(
                            v.getWindowToken(), 0);
                    startSearch(keyword, true);//去搜索
                    return true;
                }
                return false;
            }
        });
        layoutRefresh.setOnStartListener(new OnStartListener() {
            @Override
            public void onStartRefresh(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                page = 0;
                goWebSearch();
            }

            @Override
            public void onStartLoadmore(XtomRefreshLoadmoreLayout xtomRefreshLoadmoreLayout) {
                page++;
                goWebSearch();
            }
        });
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
    }

    /**
     * 判断是否添加到搜索历史，然后去服务器检索关键字
     *
     * @param str        关键字
     * @param addhistory 是否添加到搜素历史
     */
    public void startSearch(String str, boolean addhistory) {
        edtSearch.setText(str);
        edtSearch.setSelection(str.length());
        if (addhistory) {
            boolean found = false;
            if (search_strs != null && search_strs.size() > 0) {
                for (String hstr : search_strs) {
                    if (hstr.equals(str)) {
                        found = true;
                        break;
                    }
                }
            }

            if (!found) {
                if (search_strs == null)
                    search_strs = new ArrayList<String>();
                search_strs.add(0, str);
                mClient.insert(str);
            }
        }
        keyword = str;
        goWebSearch();
    }

    private void goWebSearch() {
        lstvHistory.setVisibility(View.GONE);
        layoutResult.setVisibility(View.VISIBLE);
        getNetWorker().blogList("6", "0,0", "1", "1", keyword, "", "", "", "", "", lng, lat, "", "", page + "");
    }

    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
            case BLOG_SAVEOPERATE:
                showProgressDialog("请稍候");
                break;
        }
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
            case BLOG_SAVEOPERATE:
                cancelProgressDialog();
                break;
        }
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask,
                                            HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                HemaPageArrayResult<Blog> bResult = (HemaPageArrayResult<Blog>) baseResult;
                if (bResult == null || bResult.getObjects() == null)
                    return;
                ArrayList<Blog> goods = bResult.getObjects();
                if (page == 0) {// 刷新
                    layoutRefresh.refreshSuccess();
                    layoutRefresh.setLoadmoreable(true);
                    blogs.clear();
                    blogs.addAll(goods);
                } else {//加载更多
                    layoutRefresh.loadmoreSuccess();
                    if (goods.size() > 0) {
                        blogs.addAll(goods);
                    } else {
                        layoutRefresh.setLoadmoreable(false);
                        XtomToastUtil.showShortToast(mContext, "已经到最后啦");
                    }
                }
                refreshRecycler();
                break;
            case BLOG_SAVEOPERATE:
                showTextDialog("删除成功");
//                datas.remove(curBlog);
//                refreshRecycler();
                //通知所有界面刷新
                EventBusMsg msg = new EventBusMsg();
                msg.setType(EventBusConfig.UPDATE_BLOG);
                EventBus.getDefault().post(msg);
                break;
            case FOLLOW_COLLECT_SAVEOPERATE:
                //1：添加 ;2：取消 ;3：清空
                String oper = netTask.getParams().get("oper");
                int goodcount = 0;
                if (TextUtils.isDigitsOnly(curBlog.getGoodcount())) {
                    goodcount = Integer.parseInt(curBlog.getGoodcount());
                }
                if (oper.equals("1")) {
                    curBlog.setGoodflag("1");// 收藏标记	0未收藏；1收藏
                    goodcount++;
                    View view = mContext.getLayoutInflater().inflate(R.layout.pop_zan,
                            null);
                    final PopupWindow pop = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                            LinearLayout.LayoutParams.MATCH_PARENT);
                    pop.setOutsideTouchable(true);
                    pop.setFocusable(true);
                    pop.setBackgroundDrawable(new BitmapDrawable());
                    pop.showAtLocation(mContext.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
                    new Handler().postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            pop.dismiss();
                        }
                    }, 1000);
                } else if (oper.equals("2")) {
                    curBlog.setGoodflag("0");
                    goodcount--;
                }
                curBlog.setGoodcount(goodcount+"");
                refreshRecycler();
                break;
        }
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask,
                                           HemaBaseResult baseResult) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                if (page == 0) {// 刷新
                    layoutRefresh.refreshFailed();
                } else {
                    layoutRefresh.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，" + baseResult.getMsg());
                break;
        }
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        BaseHttpInformation information = (BaseHttpInformation) netTask
                .getHttpInformation();
        switch (information) {
            case BLOG_LIST:
                if (page == 0) {// 刷新
                    layoutRefresh.refreshFailed();
                } else {
                    layoutRefresh.loadmoreFailed();
                }
                XtomToastUtil.showShortToast(mContext, "获取信息失败，请稍后再试");
                break;
        }
    }

    /**
     * 刷新
     */
    private void refreshRecycler() {
        if (blogAdapter == null) {
            blogAdapter = new LaokeAdapter(mContext, blogs);
            blogAdapter.setClickListener(this);
            blogAdapter.setTypename("0");
            recyclerView.setAdapter(blogAdapter);
            recyclerView.addItemDecoration(new RecyclerTenDecoration(mContext));
        } else {
            blogAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void OnItemClickListener(Blog blog) {
        Intent itBlog = new Intent(mContext, LaokeDetailActivity.class);
        itBlog.putExtra("blog_id", blog.getId());
        startActivity(itBlog);
    }

    @Override
    public void OnZanClickListener(final Blog blog) {
        curBlog = blog;
        loginCallBack = new LoginUtil.LoginCallBack() {
            @Override
            public void onLogin() {
                String oper = "1";//	1：添加 ;2：取消 ;3：清空
                if (blog.getGoodflag().equals("1")) {// 点赞标记	0无 1有
                    oper = "2";
                } else {
                    oper = "1";
                }
                getNetWorker().FolColOperate(user.getToken(), "3", oper, blog.getId());
                loginCallBack = null;
            }
        };
        LoginUtil.getInstance(mContext, loginCallBack);
    }

    @Override
    public void OnCommentClickListener(final Blog blog) {
        loginCallBack = new LoginUtil.LoginCallBack() {
            @Override
            public void onLogin() {
                Intent itComment = new Intent(mContext, ReleaseBlogActivity.class);
                itComment.putExtra("type", 2);
                itComment.putExtra("blog_id", blog.getId());
                startActivity(itComment);
                loginCallBack = null;
            }
        };
        LoginUtil.getInstance(mContext, loginCallBack);
    }

    @Override
    public void OnDeleteClickListener(final Blog blog) {
        curBlog = blog;
        HemaButtonDialog hbDialog = new HemaButtonDialog(mContext);
        hbDialog.setText("确定删除?");
        hbDialog.setLeftButtonText("取消");
        hbDialog.setRightButtonText("确定");
        hbDialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
        hbDialog.setButtonListener(new HemaButtonDialog.OnButtonListener() {

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
                getNetWorker().blogSaveoperate(BaseApplication.getInstance().getUser().getToken(),
                        "1", blog.getId());
            }

        });
    }

    @Override
    public void OnItemClickListener(String key) {
        startSearch(key, false);
    }

    @Override
    public void OnClearClickListener() {
        HemaButtonDialog lodialog = new HemaButtonDialog(mContext);
        lodialog.setText("确定要清除历史记录？");
        lodialog.setRightButtonText("确定");
        lodialog.setRightButtonTextColor(getResources().getColor(R.color.theme_orange));
        lodialog.setLeftButtonText("取消");
        lodialog.setButtonListener(new OnButtonListener() {

            @Override
            public void onRightButtonClick(HemaButtonDialog dialog) {
                mClient.clear();
                search_strs.clear();
                historyAdapter.notifyDataSetChanged();
                dialog.cancel();
            }

            @Override
            public void onLeftButtonClick(HemaButtonDialog dialog) {
                dialog.cancel();
            }
        });
    }

    private class LoadDBTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            // XtomProcessDialog.show(mContext, R.string.loading);
        }

        @Override
        protected Void doInBackground(Void... params) {
            search_strs = mClient.select();
            return null;
        }

        @Override
        protected void onPostExecute(Void v) {
            if (search_strs == null || search_strs.size() == 0) {
                return;
            }
            historyAdapter = new SearchHistoryAdapter(mContext, search_strs, LaokeSearchActivity.this);
            lstvHistory.setAdapter(historyAdapter);
        }
    }

    @OnClick({R.id.tv_cancel, R.id.layout_return_top})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.layout_return_top:
                recyclerView.smoothScrollToPosition(0);
                break;
        }
    }

    @Subscribe
    public void onEventMainThread(EventBusMsg msg) {
        if (msg.getType() == EventBusConfig.USER) {
            this.user = msg.getUser();
            if (loginCallBack != null)
                loginCallBack.onLogin();
        }else if (msg.getType() == EventBusConfig.UPDATE_BLOG
                || msg.getType() == EventBusConfig.UPDATE_REPLY_ADD
                || msg.getType() == EventBusConfig.UPDATE_REPLY_REMOVE) {
            layoutRefresh.getOnStartListener().onStartRefresh(layoutRefresh);
        }
    }
}
